package com.wang.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.omg.CosNaming.NamingContextExtPackage.AddressHelper;

import com.wang.dao.impl.HomeworkDaoImpl;
import com.wang.domain.Homework;
import com.wang.domain.Student;
import com.wang.homework.UnZip;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/list")
public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final HomeworkDaoImpl homeworkDaoImpl;
	static{
		homeworkDaoImpl = new HomeworkDaoImpl();
	}
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if("yes".equals(request.getParameter("upload"))){
			response.sendRedirect("/home/jsp/contentList/upload.jsp");
			return;
		}
		List<Homework> findAll = homeworkDaoImpl.findAll();
		request.setAttribute("lists", findAll);
		request.getRequestDispatcher("/jsp/contentList/list.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if("yes".equals(request.getParameter("isupload"))){
			doUpload(request);
			response.sendRedirect("/home/list");
			return;
		}
		request.getRequestDispatcher("/jsp/contentList/upload.jsp").forward(request, response);
	}

	private void doUpload(HttpServletRequest req) throws IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		File fileZip = null;
		try {
			List<FileItem> parseRequest = servletFileUpload.parseRequest(req);
			for (FileItem fileItem : parseRequest) {
				if(!fileItem.isFormField()){
					if(fileItem.getSize()>0){
						String realPath = req.getServletContext().getRealPath("/upload");
						String name = UUID.randomUUID().toString().replaceAll("-", "")+"_"+FilenameUtils.getName(fileItem.getName());
						File file = new File(realPath);
						if (!file.exists()) {
							file.mkdirs();
						}
						InputStream inputStream = fileItem.getInputStream();
						fileZip = new File(realPath, name);
						FileOutputStream fileOutputStream = new FileOutputStream(fileZip);
						BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
						IOUtils.copy(inputStream, bufferedOutputStream);
						bufferedOutputStream.close();
						fileOutputStream.close();
						inputStream.close();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} finally {
			String format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss").format(new Date());
			dealHomework(fileZip,req);
			UnZip.deleteDir(fileZip);
			UnZip.deleteDir(new File(fileZip.getParent(),fileZip.getName().substring(0, fileZip.getName().lastIndexOf("."))));
			new HomeworkDaoImpl().add(format, format, ((Student)req.getSession().getAttribute("LOGIN_IN_SESSION")).getId());
		}
	}

	private void dealHomework(File fileZip,HttpServletRequest req) throws FileNotFoundException {
		UnZip unZip = new UnZip((Student)req.getSession().getAttribute("LOGIN_IN_SESSION"));
		File unzip2 = unZip.unzip(fileZip);
		unZip.foreachDir(unzip2);
	}
	
}
